package app.utils;

import java.util.Properties;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.FactoryBean;

public class DataSourcePropertiesEncryptFactoryBean implements FactoryBean {

	private static final Logger log = LogManager
			.getLogger(DataSourcePropertiesEncryptFactoryBean.class);
	private Properties properties;

	@Override
	public Object getObject() throws Exception {
		return getProperties();
	}

	@Override
	public Class getObjectType() {
		return java.util.Properties.class;
	}

	@Override
	public boolean isSingleton() {
		return true;
	}

	public Properties getProperties() {
		return properties;
	}

	public void setProperties(Properties inProperties) {
		this.properties = inProperties;
		String encrypted = properties.getProperty("encrypted");
		String originalUsername = properties.getProperty("user");
		String originalPassword = properties.getProperty("password");
		if (encrypted.equals("true")) {
			System.out.println("DataSourceProperties needs Decrypted");
			AsymmetricEncryption instance = new AsymmetricEncryption();
			String privateKeyString = "30820275020100300d06092a864886f70d01010105000482025f3082025b0201000281810083d2e272e256e483313ad8ea4b8bacb81860bff238b03388acf98f664a50465f58ad22de7f864662f5ef60fbc0807f92a854173f9d69ce4371af41877e6caa124df0b020f7e13c49ba2bdabf43b6e7e81e9ac953e7c40f137db4bcb54b6fa180020354d97276d076ff80191485d926690c7d9551a246fea80583f6475afd5b6102030100010281807dc9955b9aaedf8e70437f08d2dd8d0a7df8943045f79cb526995c447754f251b9043ce9a33635a3e8996b29cf1ece9cdb12a2bc89309529b6294d964504dba30950085208449bf172987d12a5575272064379b99c8450d2d5a8a67095656451a38e3860ec2f2397d9c5023836f5078cae6179d61d1046ef0cc7bac069dc2f21024100d5369c964bcd4bcb3be5a8c0d472f1c1cb39950b68e85ed4076e8a1481f3bffb4bd2234ca7c5dc93e08260c0117b93ad3055557d154cecc64c931bbc67cbf98f0241009e470dffa651d16c52cee43c0f01f90f122756286036a4ca07a223fbf1e795f859727aaeab1eecd9aad7bf597e3bfa8aa581a751b8eec9ac31f4322dcae4840f02404fcb5b79082f71f1429e65b49d0dd39a92831f5ba0cc6e48edeb19b4291a5f3c1e192bead1534484f75df3f58dd570e43d1582a40867bca94e19342523b77bd3024065a1b6896be0a99ae6e95680821a80347f31a70f3208a473ddc6ed584012b6a7cbb7c8b313ca3dc7defdbe2ed6f1e884d295983ccf84f5168ed500cb8ab6855d0240352519c23d66cf06bb7867513f32eaebc14d2312c77d34f7605b068530f1137c71c3cbbf8a99421267e56a26b86082dc21380ae5c9fc1029d5b69cb333a326a4";
			// 解密操作
			try {
				String newUsername = instance.decodeByPrivatekey(
						privateKeyString, originalUsername);
				properties.put("user", newUsername);

				String newPassword = instance.decodeByPrivatekey(
						privateKeyString, originalPassword);
				properties.put("password", newPassword);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}else {
			System.out.println("DataSourceProperties don't needs Decrypted");
		}
	}
}
